package com.ssm.order.controller;

import com.ssm.dto.CommonResult;
import com.ssm.model.order.OrderModel;
import com.ssm.model.stock.StockModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

@RestController
public class RestTemplateDemoController {

    @Autowired
    private RestTemplate restTemplate;

    @GetMapping("/hello2")
    public CommonResult<OrderModel> hello2() {
        ParameterizedTypeReference<CommonResult<StockModel>> typeRef =
                new ParameterizedTypeReference<CommonResult<StockModel>>() {
                };
        ResponseEntity<CommonResult<StockModel>>
                forEntity = restTemplate.exchange("http://stock-service/getStockDetail", HttpMethod.GET,
                HttpEntity.EMPTY, typeRef);
        OrderModel orderModel = new OrderModel();
        orderModel.setId(100);
        orderModel.setCode("100-100");
        if (Objects.equals(forEntity.getStatusCode(), HttpStatus.OK) && Objects.nonNull(forEntity.getBody())) {
            CommonResult<StockModel> result = forEntity.getBody();
            if (result.getCode() != 1) {
                return CommonResult.error(null, result.getCode(), result.getMessage());
            }
            orderModel.setStockModel(result.getData());
        }
        return CommonResult.success(orderModel);
    }

}
